<?php

/**
 * AmplifyCMS
 *
 * This file is part of AmplifyCMS.
 *
 * AmplifyCMS is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * AmplifyCMS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author Rodrigo Rutkoski Rodrigues, <rutkoski@gmail.com>
 * @copyright Copyright 2008 Rodrigo Rutkoski Rodrigues
 */

require_once('users_amp_controller.php');

/**
 * 
 * @author Rodrigo Rutkoski Rodrigues <rutkoski@gmail.com>
 *
 */
class UsersController extends UsersAmpController
{

  /**
   *
   */
  protected function action_index($offset = 0, $limit = 10)
  {
    parent::action_index();
    
    $count = $this->db->query('SELECT COUNT({User.id}) AS total from {User}')->fetchColumn();
    
    $pager = new Pager($count, $this->response->get('limit'), $this->response->get('offset'));
    
    $users = $this->db->from('User')->orderBy($this->response->get('order'))->offset($this->response->get('offset'))->limit($this->response->get('limit'))->find();
    
    $this->response->set('users', $users);
    $this->response->set('pager', $pager);
  }

  /**
   *
   */
  protected function action_view($id = null)
  {
    try {
      $this->validateId($id);
      $this->response->set('user', $this->db->load('User', $id));
    }
    
    catch (ParameterException $e) {
      $this->response->warning($e->getMessage());
      return $this->response->redirect('/users');
    }
    
    catch (NotFoundException $e) {
      $this->response->warning(__('User not found'));
      return $this->response->redirect('/users');
    }
  }

  /**
   *
   */
  protected function action_create()
  {
    $this->response->set('formTitle', __('Create User'));
    return $this->response->redirectIf($this->form() !== false, '/users');
  }

  /**
   *
   */
  protected function action_edit($id = null)
  {
    try {
      $this->validateId($id);
      $this->response->set('formTitle', __('Edit User'));
      return $this->response->redirectIf($this->form($id) !== false, '/users');
    }
    
    catch (ParameterException $e) {
      $this->response->warning($e->getMessage());
      return $this->response->redirect('/users');
    }
    
    catch (NotFoundException $e) {
      $this->response->warning(__('User not found'));
      return $this->response->redirect('/users');
    }
  }

  /**
   *
   */
  protected function action_your_profile()
  {
    $this->response->set('formTitle', __('Your Profile'));
    $this->form($this->app->getUser()->get('id'));
  }

  /**
   *
   */
  protected function action_delete($id = null)
  {
    try {
      $this->validateId($id);
      $this->db->delete('User', $id);
      $this->response->notice(__('User deleted'));
    }
    
    catch (ParameterException $e) {
      $this->response->warning($e->getMessage());
    }
    
    catch (NotFoundException $e) {
      $this->response->warning(__('User not found'));
    }
    
    return $this->response->redirect('/users');
  }

  /**
   *
   */
  private function form($id = null)
  {
    if (empty($id)) {
      $user = new User();
    }
    else {
      $user = $this->db->load('User', $id);
    }
    
    $this->response->set('user', $user);
    $this->response->set('roles', $this->getRolesList());
    
    $locales = Simplify::getL10n()->getAvailableLocales();
    $this->response->set('locales', $locales);
    
    $roles = $user->getRoles();
    $this->response->set('user_roles', ArrayList::from($roles, 'id', null));
    
    $this->setTemplate($user->id == 1 ? 'admin_form' : 'users_form');
    
    if ($this->form) {
      try {
        $role_ids = $this->form->get('role_id', array());
        $roles = $user->getRoles();
        $roles->removeAll();
        foreach ($role_ids as $role_id) {
          $roles->add($this->db->load('Role', $role_id));
        }
        
        $user->copyAll($this->form, array(
          'password_a', 'password_b', 'role_id' 
        ));
        
        $user->setPassword($this->form->password_a, $this->form->password_b);
        $user->validateAll();
        $this->db->save($user);
        $this->response->notice(__('Data saved'));
        return $user;
      }
      
      catch (EmptyException $e) {
        $this->response->notice(__('Nothing to save'));
      }
      
      catch (ValidationException $e) {
        $this->response->warning($user->getErrors());
      }
    }
    
    return false;
  }

  /**
   *
   * @return array Associative array of role.id => role.name
   */
  private function getRolesList()
  {
    $level = $this->app->getUser()->getMinLevel();
    
    $roles = $this->db->from('Role')->select('{Role.id}, {Role.name}')->where('{Role.id} != ? AND {Role.level} >= ?', array(
      2, $level 
    ))->find();
    
    return ArrayList::from($roles, 'name');
  }

}

?>